package com.syncomponents.remoting;

import java.io.IOException;
import java.nio.charset.Charset;

import javax.annotation.Resource;

import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluentx.Request;
import org.apache.http.client.fluentx.UrlBuilder;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.syncomponents.context.annotation.ClientComponent;
import com.syncomponents.core.RequestException;
import com.syncomponents.remoting.message.HttpMessageRequest;
import com.syncomponents.util.BaseConstant;

/**
 * http请求类
 * 
 * @author sunkey
 * @date Jan 13, 2014
 */
@ClientComponent(type = "http")
public class HttpHandlerClient extends AbstractClient<HttpMessageRequest> {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpHandlerClient.class);

    @Resource
    private ClientFactory clientFactory;

    /**
     * 执行请求
     * 
     * @param messageRequest
     * @return
     */
    public String doExcute(HttpMessageRequest messageRequest) {
        LOGGER.info("messageRequest:{}", messageRequest.toString());
        String response = realExecute(messageRequest);

        LOGGER.info("request url:{}, response:{}",
                messageRequest.getHttpHost().toHostString() + messageRequest.getUrl(), response);

        return response;
    }

    /**
     * 封装request对象
     * 
     * @param messageRequest
     * @return
     */
    private Request getRequest(HttpMessageRequest messageRequest) {
        final String uri = UrlBuilder.url(messageRequest.getHttpHost(), messageRequest.getUrl()).build();
        Request request = Request.Method(messageRequest.getMethod(), uri).addHeader(HttpHeaders.ACCEPT,
                messageRequest.getContentType());
        if (messageRequest.getContent() != null) {
            request.bodyString(messageRequest.getContent().toString(),
                    ContentType.create(messageRequest.getContentType(), Charset.forName(BaseConstant.ENCODE_TYPE_UTF8)));
        }
        return request;
    }

    /**
     * 执行请求
     * 
     * @param httpRequst 请求类
     * @return 返回消息
     */
    private String realExecute(HttpMessageRequest messageRequest) {
        LOGGER.info("request url:{}", messageRequest.getHttpHost().toHostString());
        try {
            return getRequest(messageRequest).execute().returnContent().toString();
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RequestException(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RequestException(e.getMessage(), e);
        }
    }

}
